package com.jyy.prefabricated.utils;

import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletOutputStream;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Map;

public class PdfUtils {
    private final static Logger log = LoggerFactory.getLogger(PdfUtils.class);

    /**
     * 利用模板生成pdf
     *
     * @param o            写入的数据
     * @param outputStream 自定义保存pdf的文件流
     * @param templatePath pdf模板路径
     */
    public static void generatePdfByTemplate(Map<String, Object> o, ServletOutputStream outputStream,
                                             String templatePath) {
        PdfReader reader;
        ByteArrayOutputStream bos;
        PdfStamper stamper;
        try {
            // 读取pdf模板
            reader = new PdfReader(templatePath);
            bos = new ByteArrayOutputStream();
            stamper = new PdfStamper(reader, bos);

            // 设置使用itext-asian.jar的中文字体 */
            BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

            ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
            fontList.add(bf);
            AcroFields fields = stamper.getAcroFields();
            fields.setSubstitutionFonts(fontList);
            //文字类的内容处理
            Map<String, String> datemap = (Map<String, String>) o.get("datemap");
            for (String key : datemap.keySet()) {
                String value = datemap.get(key);
                fields.setField(key, value);
            }
            //图片类的内容处理（二维码）
            Map<String, Image> imgmap = (Map<String, Image>) o.get("imgmap");
            if (imgmap != null) {
                for (String key : imgmap.keySet()) {
                    Image value = imgmap.get(key);
                    Image image = value;
                    int pageNo = fields.getFieldPositions(key).get(0).page;
                    Rectangle signRect = fields.getFieldPositions(key).get(0).position;
                    float x = signRect.getLeft();
                    float y = signRect.getBottom();
                    //获取图片页面
                    PdfContentByte under = stamper.getOverContent(pageNo);
                    // 根据域的大小缩放图片
                    image.scaleToFit(signRect.getWidth(), signRect.getHeight());
                    //添加图片
                    image.setAbsolutePosition(x, y);
                    under.addImage(image);
                }
            }
           // 图片类的内容处理(证件照图片)
            Map<String, Image> certificatemap = (Map<String, Image>) o.get("certificatemap");
            if (certificatemap != null) {
                for (String key : certificatemap.keySet()) {
                    Image value = certificatemap.get(key);
                    Image image = value;
                    int pageNo = fields.getFieldPositions(key).get(0).page;
                    Rectangle signRect = fields.getFieldPositions(key).get(0).position;
                    float x = signRect.getLeft();
                    float y = signRect.getBottom();
                    //获取图片页面
                    PdfContentByte under = stamper.getOverContent(pageNo);
                    /*图片放在位置*/
                    image.setAbsolutePosition(x, y);
                    /*缩放图像到绝对宽度和绝对高度*/
                    image.setAlignment(Image.UNDERLYING);
                   // image.scaleAbsolute(77,107);
                     image.scaleAbsolute(100,150);
                    /*添加图片*/
                    under.addImage(image);
                }
            }
            // 如果为false那么生成的PDF文件还能编辑，一定要设为true
            stamper.setFormFlattening(true);
            stamper.close();

            Document doc = new Document();
            PdfCopy copy = new PdfCopy(doc, outputStream);
            copy.setEncryption(null, "095215".getBytes(), PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128);
            doc.open();
            PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
            copy.addPage(importPage);
            doc.close();


        } catch (Exception e) {
            // TODO: handle exception
            throw new RuntimeException(e.getMessage(), e.getCause());
        }
    }

    /**
     * 流转化为字节
     *
     * @param inStream
     * @return
     * @throws IOException
     */
    public static byte[] inputstream2Bytes(InputStream inStream) throws IOException {
        byte[] in_b = null;
        try {
            ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
            //buff用于存放循环读取的临时数据
            byte[] buff = new byte[100];
            int rc = 0;
            while ((rc = inStream.read(buff, 0, 100)) > 0) {
                swapStream.write(buff, 0, rc);
            }
            //in_b为转换之后的结果
            in_b = swapStream.toByteArray();

        } catch (Exception e) {
            log.error("inputstream2Bytes", e);
        } finally {
            inStream.close();
        }
        return in_b;
    }

    /**
     * 文件转流
     *
     * @param file
     * @return
     * @throws IOException
     */
    public static InputStream file2InputStream(File file) throws IOException {
        return new FileInputStream(file);
    }

    /**
     * 将inputStream转化为file
     *
     * @param is
     * @param file 要输出的文件目录
     */
    public static void inputStream2File(InputStream is, File file) throws IOException {
        OutputStream os = null;
        try {
            os = new FileOutputStream(file);
            int len = 0;
            byte[] buffer = new byte[8192];

            while ((len = is.read(buffer)) != -1) {
                os.write(buffer, 0, len);
            }
        } finally {
            os.close();
            is.close();
        }
    }
}
